import json

from django.core.paginator import Paginator
from django.db import transaction, DatabaseError
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View

from aijia_mall import settings
from apps.areas.models import House, Facility
from utils.views import LoginRequiredJSONMin
from utils.views import LoginRequiredJSONMin
# Create your views here.
from django.views import View
from apps.areas.models import House
from apps.areas.models import HouseImage
from libs.qiniu.qiniu_storage import storage
from qiniu import Auth,put_data


class GetHomeInfoView(View):

    # GET /api/v1.0/houses?aid=1&sd=2021-01-21&ed=2021-01-22&sk=new&p = 1
    def get(self, request):
        """
        房屋数据搜索
        """
        data = request.GET
        aid = data.get('aid')
        start_day = data.get('sd')
        end_day = data.get('ed')
        sort_key = data.get('sk', 'new')
        page = data.get('p', 1)

        if sort_key == 'booking':
            # 订单量从高到低
            houses_query = House.objects.filter().all().order_by("-order_count")
        elif sort_key == 'price-inc':
            # 价格从低到高
            houses_query = House.objects.filter().all().order_by("price")
        elif sort_key == 'price-des':
            # 价格从高到低
            houses_query = House.objects.filter().all().order_by("-price")
        else:
            # 默认以最新的时间进行排序
            houses_query = House.objects.filter().all().order_by("-create_time")

        paginator = Paginator(houses_query, per_page=5)
        page_houses = paginator.page(page)
        total_num = paginator.num_pages

        houses_list = []

        for item in page_houses:
            houses_list.append({
                "address": item.address,
                "area_name": "东城区",
                "ctime": item.create_time,
                "house_id": item.id,
                "img_url": item.index_image_url,
                "order_count": item.order_count,
                "price": item.price,
                "room_count": item.room_count,
                "title": item.title,
                "user_avatar": None
            })

        data = {
            "total_page": total_num,
            "houses": houses_list
        }
        return JsonResponse({"errno": 0, "errmsg": "请求成功", "data": data})


class MyHomeInfoView(LoginRequiredJSONMin, View):

    def post(self, request):
        """
        发布房源
        """
        user = request.user
        # 获取房源参数
        data = json.loads(request.body.decode())
        # 提取房源参数
        title = data.get('title')  # 标题
        price = data.get('price')  # 价格
        area_id = data.get('area_id')  # 城区id
        address = data.get('address')  # 房屋地址
        room_count = data.get('room_count')  # 房间数目
        acreage = data.get('acreage')  # 房屋面积
        unit = data.get('unit')  # 房屋单元，如：几室几厅
        capacity = data.get('capacity')  # 房屋容纳的人数
        beds = data.get('beds')  # 房屋床铺的配置
        deposit = data.get('deposit')  # 房屋押金
        min_days = data.get('min_days')  # 最少入住天数
        max_days = data.get('max_days')  # 最大入住天数，0表示不限制
        facility_ids = data.get('facility')  # 用户选择的设施信息id列表，如：[7, 8]
        # 验证房源参数
        if not all([title, price, area_id, address, room_count, acreage, unit, capacity,
                    beds, deposit, min_days, max_days]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 最少入住天数不能小于0
        if eval(min_days) < 0 or eval(max_days) < 0:
            return JsonResponse({"errno": 400, "errmsg": "参数错误"})
        try:
            # 将 price 和 deposit进行数据类型转换因为获取的这两个数据是字符串类型, 数据库中是int
            # 数据里这两个单位是分
            price = int(float(price) * 100)
            deposit = int(float(deposit) * 100)
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 400, "errmsg": "参数错误"})

        # 因为添加数据的时候 对同一个对象会操作两次 使用事件
        with transaction.atomic():
            save_id = transaction.savepoint()
            # 保存数据
            try:
                house = House.objects.create(user=user, title=title, price=price, area_id=area_id, address=address,
                                             room_count=room_count,
                                             acreage=acreage, unit=unit, capacity=capacity, beds=beds,
                                             deposit=deposit, min_days=min_days, max_days=max_days)
            except DatabaseError as e:
                print(e)
                transaction.savepoint_rollback(save_id)
                return JsonResponse({"errno": 400, "errmsg": "数据库保存失败"})

            # 添加设施  房间表和设施表是多对多的关系  facility_ids 中保存的是设施的id
            try:
                if facility_ids:
                    # facility_ids 不为空 则查找对应的设施名字 in表示范围查询, 是否包含在范围内
                    facilitys = Facility.objects.filter(id__in=facility_ids)
                    for facility in facilitys:
                        house.facility.add(facility)
            except DatabaseError as e:
                print(e)
                transaction.savepoint_rollback(save_id)
                return JsonResponse({"errno": 400, "errmsg": "数据库保存失败"})
            transaction.savepoint_commit(save_id)
        return JsonResponse({"errno": 0, "errmsg": "发布成功", "data": {"house_id": house.id}})


class MyHomeListView(LoginRequiredJSONMin, View):

    def get(self, request):
        """
        我的房屋列表
        """
        user = request.user
        my_house = House.objects.filter(user=user)
        houses = []
        for house in my_house:
            houses.append({
                "house_id": house.id,
                "order_count": house.order_count,
                "title": house.title,
                "ctime": house.create_time,
                "price": house.price,
                "area_name": house.area_id,
                "address": house.address,
                "room_count": house.room_count,
                "img_urls": house.index_image_url,
                "user_avatar": None
            })

        return JsonResponse({
            'errno': 0,
            'errmsg': 'ok',
            'data': {
                "houses": houses
            }
        })


access_key = 'PCulTwc2C7DKq5ykfYrUd5JWEOgLzmo-bfDWqRnE'
secret_key = 'g2ZtNzwC1FQShHRulm4i4K9uazOJRuYc5RWdElnf'
bucket_name = 'aijiaoy'
secure_url = 'http://qn41u710y.hn-bkt.clouddn.com/'

# # 上传房源照片
class ImageInfoView(LoginRequiredJSONMin, View):

    def post(self, request, house_id):
        # 接受参数
        image = request.FILES.get('house_image')
        key = 'image_%s'%image
        q = Auth(access_key,secret_key)
        token = q.upload_token(bucket_name,key,3600)
        print(token)

        # 判断参数是否存在
        if not image:
            return JsonResponse({'code': 400, 'errmsg': '缺失必传参数'})
        # 验证房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except DatabaseError as e:
            print(e)
            return JsonResponse({"errno": 400, "errmsg": "该房间不存在"})
        # file_data = image.read()
        # 验证通过，上传文件到七牛云
        # try:
        #     key = storage(file_data)
        # except Exception as e:
        #     print(e)
        #     return JsonResponse({"errno": 400, "errmsg": "上传图片失败"})
        # 保存图片到数据库 需要操作的数据库有 house 保存房屋的 主图片 以及 房屋图片 因为操作两个数据库所以使用 事务
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                # 判断 house中的 主图片是否有 没有的话,则添加
                if not house.index_image_url:
                    house.index_image_url = key
                    house.save()
                house_image = HouseImage(house=house, url=key)
                house_image.save()
            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)
                return JsonResponse({"errno": 400, "errmsg": "上传图片失败"})
            else:
                transaction.savepoint_commit(save_id)

        data = {"url": secure_url + key}
        ret = put_data(token,key,image)
        print(ret)
        return JsonResponse({"errno": 0, "errmsg": "图片上传成功", "data": data})


class IndexHomeView(View):

    def get(self, request):
        """
        首页房屋推荐
        """
        # 使用切片获取 五间房屋的数据
        # 应该 对其进行排序 选择排名靠前的五家  按照该房屋的订单数进行排序
        try:
            houses = House.objects.order_by("-order_count")[0:5]
        except DatabaseError as e:
            print(e)
            return JsonResponse({"errno": 400, "errmsg": "数据库查询失败"})
        # 构造返回的数据
        index_list = []
        for house in houses:
            index_list.append({
                "house_id": house.id,
                "img_url": house.index_image_url,
                "title": house.title
            })

        return JsonResponse({
            'data': index_list,
            'errmsg': 'ok',
            'errno': 0
        })
